<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="`${isUpdate ? '编辑' : '新增'}账号`" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { accountFormSchema } from './account.data';
  import { updateAdminUser, createAdminUser } from "@/api/admin/admin_user";
  import {useMessage} from "@/hooks/web/useMessage";

  defineOptions({ name: 'AccountModal' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const rowId = ref('');
  const { createMessage } = useMessage()

  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      await setFieldsValue({
        ...data.record,
      });
    }

    await updateSchema([
      {
        field: 'password',
        ifShow: !unref(isUpdate),
      },
    ]);
    await updateSchema([
      {
        field: 'password1',
        ifShow: !unref(isUpdate),
      },
    ]);
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      let response = null;
      if (unref(isUpdate)){
        response = await updateAdminUser({ ...values, id: rowId.value })
      } else {
        response = createAdminUser(values);
      }
      const { code, msg } = response;
      if (0 === code){
        createMessage.success(`添加成功！`);
        closeModal();
        emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
      } else {
        createMessage.error(msg ? msg : `添加失败`);
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
